package easier.websocket;

import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.List;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ClientHandshake;

public class WebSocketServerImpl extends org.java_websocket.server.WebSocketServer {

    public WebSocketServerImpl() {

    }

    public WebSocketServerImpl( int port ) {

        this( new InetSocketAddress( "localhost", port ) );
    }


    public WebSocketServerImpl( InetSocketAddress address ) {

        super( address );
    }

    public WebSocketServerImpl( InetSocketAddress address, int decodercount ) {

        super( address, decodercount );
    }

    public WebSocketServerImpl( InetSocketAddress address, List< Draft > drafts ) {

        super( address, drafts );
    }

    public WebSocketServerImpl( InetSocketAddress address, int decodercount, List< Draft > drafts ) {

        super( address, decodercount, drafts );
    }

    public WebSocketServerImpl( InetSocketAddress address, int decodercount, List< Draft > drafts,
        Collection< WebSocket > connectionscontainer ) {

        super( address, decodercount, drafts, connectionscontainer );
    }

    @Override
    public void onOpen( WebSocket conn, ClientHandshake handshake ) {

        /*向客户端发送*/
        conn.send( "welcome to server!" );
        /*向所有客户端发送*/
        broadcast( "new connection: " + handshake.getResourceDescriptor() );
        System.out.println( "server:" + conn.getRemoteSocketAddress() + " enter the room" );

    }

    @Override
    public void onClose( WebSocket conn, int code, String reason, boolean remote ) {

        broadcast( conn + " has left room" );
        System.out.println( "server:" + conn.getRemoteSocketAddress() + " has left room" );
    }

    @Override
    public void onMessage( WebSocket conn, String message ) {

        broadcast( message );
        System.out.println( "server:" + conn.getRemoteSocketAddress() + " send message: " + message );
    }

    @Override
    public void onError( WebSocket conn, Exception ex ) {

        ex.printStackTrace();
    }

    @Override
    public void onStart() {

        System.out.println( "server:" + "start " + getAddress() );
        setConnectionLostTimeout( 500 );
    }
}
